package com.hui.stock.security.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hui.stock.utils.JwtTokenUtil;
import com.hui.stock.vo.resp.R;
import com.hui.stock.vo.resp.ResponseCode;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author: ymh
 * @date: 2025/1/13 10:48
 * @description: 定义授权过滤器，核心作用：
 *  *      1.过滤请求，获取请求头中的token字符串
 *  *      2.解析token字符串，并获取token中信息：username role
 *  *      3.将用户名和权限信息封装到UsernamePasswordAuthenticationToken票据对象下
 *  *      4.将票据对象放入安全上下文，方便校验权限时，随时获取
 */
public class JwtAuthorizationFilter extends OncePerRequestFilter {

    /**
     * 访问过滤的方法
     * @param request
     * @param response
     * @param filterChain
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //1 从请求头中获取票据
        String authorization = request.getHeader(JwtTokenUtil.TOKEN_HEADER);
        //2 判断票据是否存在
        if (authorization==null){
            //为空表示没有认证，放行去认证
            filterChain.doFilter(request, response);
            return;
        }
        //3 解析票据，获取用户名和权限
        Claims claims = JwtTokenUtil.checkJWT(authorization);
        if (claims==null){
            //说明 票据解析出现异常，票据就失效了
            R<Object> r = R.error(ResponseCode.INVALID_TOKEN);
            String respStr = new ObjectMapper().writeValueAsString(r);
            response.setContentType(MediaType.APPLICATION_JSON_VALUE);
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(respStr);
            return;
        }
        String username = JwtTokenUtil.getUsername(authorization);
        //生成token时，权限字符串的格式是：[P8,ROLE_ADMIN]
        String userRole = JwtTokenUtil.getUserRole(authorization);
        //生成权限集合对象 P8,ROLE_ADMIN
        String strip = StringUtils.strip(userRole, "[]");
        List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(strip);
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username,null,authorities);
        //4将用户权限封装到安全上下文中,这样，线程无论走到哪里，都可以获取token对象，验证当前用户访问对应资源是否被授权
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request,response);
    }
}
